package com.edu.demo.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName: ServletUtils
 * @Description:
 * @Author: jxw
 * @Date: 2023-01-25
 */
public class ServletUtils {
    public static void renderString(HttpServletResponse response,String str){
        try {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(str);
//            response.getWriter().print(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static HttpServletRequest getHttpServletRequest(){
        ServletRequestAttributes requestAttributes = ServletRequestAttributes.class.
                cast(RequestContextHolder.getRequestAttributes());
        return  requestAttributes.getRequest();
    }

    public static String getHeader(String headerKey){
        HttpServletRequest request = getHttpServletRequest();
        return request.getHeader(headerKey);
    }
}
